package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
    //文件上传
    @RequestMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file);
        //TODO 上传文件到本地文件夹
        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        //判断文件是否为空
        if (Objects.isNull(originalFilename)) {
           return Result.error(MessageConstant.FILE_NOT_NULL);
        }
        //获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成新的文件名
        String newFilename = System.currentTimeMillis() + suffix;
        //获取文件上传路径
        String uploadPath = "D:/upload/";
        //创建路径
        Path path = Paths.get(uploadPath);
            try {
                Files.createDirectory(path);
            } catch (Exception e) {
                log.error("创建路径失败：{}", e.getMessage());
                return Result.error(MessageConstant.UPLOAD_FAILED);
            }
        //保存文件
        try {
            file.transferTo(Paths.get(uploadPath + newFilename));
        } catch (Exception e) {
            log.error("保存文件失败：{}", e.getMessage());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        //返回文件路径
        return Result.success(uploadPath + newFilename);
    }

    //文件下载
    @RequestMapping("/download")
    public Result<String> download() {
        //TODO 下载文件到本地文件夹
        //返回文件路径
        return Result.success();
    }

}
